package com.gmrz.uap.common;

import org.apache.commons.lang3.StringEscapeUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

public class ParamFilter implements Filter {
    private static String flt = null;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 获取在web.xml配置好的需要拦截的字符串
        flt = filterConfig.getInitParameter("flt");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        HttpServletRequest wrapper = new RequestWrapper(request);//定义一个新的request（名称是wrapper），
        filterChain.doFilter(wrapper, response);//继续执行过滤器链
    }

    @Override
    public void destroy() {

    }

    private static class RequestWrapper extends HttpServletRequestWrapper {//这里用的是内部类，也可以不用

        private Map<String, String[]> params = new HashMap<String, String[]>();//将request对象中的参数修改后，放在这个集合里，随后项目取的所有Parameter都是从这个集合中取数

        public RequestWrapper(HttpServletRequest request) throws UnsupportedEncodingException {//定义构造函数
            super(request);//将request交给父类
            //先通过request原生的方法，遍历获取到的参数
            Enumeration enu=request.getParameterNames();
            while (enu.hasMoreElements()) {
                //得到参数名
                String name = enu.nextElement().toString();
                //得到参数对应值
                String[] value = request.getParameterValues(name);
                if(null != value){
                    List<String> list = new ArrayList<String>();
                    for(String s : value){
                        // StringEscapeUtils.escapeHtml4（）防止html脚本注入，拦截一些“<  >等”
                        list.add(filterContent(s));
                    }
                    value =  list.toArray(value);
                }
                params.put(name, value);
            }
            //将修改好的params重新放入RequestWrapper对象中
            //addParameters(request,params);
        }
        @Override
        public String getParameter(String name) {
            String[]values = params.get(name);
            if(values == null || values.length == 0) {
                return null;
            }

            return values[0];
        }
        @Override
        public Enumeration<String> getParameterNames() {
            Vector<String> v = new Vector<String>();
            Set<Map.Entry<String, String[]>> entrySet = params.entrySet();
            for (Map.Entry<String, String[]> entry : entrySet) {
                v.add(entry.getKey());
            }
            Enumeration<String> en =  v.elements();

            return v.elements();
        }

        @Override
        public String[] getParameterValues(String name) {
            String[] strArray =  params.get(name);
            return strArray;
        }
        @Override
        public Map<String,String[]> getParameterMap(){
            return params;
        }

        public String filterContent(String content){
            String[] filter = flt.split("\\|");
            for(int i=0; i < filter.length; i++) {
                if(content.contains(filter[i])) {
                    // 将请求中出现需要被拦截的字符串时，将其替换为@符
                    content = content.replaceAll(filter[i], "@");
                }
            }
            return content;
        }
    }
}
